var CLIENT_VERSION = '1.0';

function Stars(options, canvas) {
    var self = this;
    this.options = options;
    this.canvas = canvas;
    this.globalAlpha = 1;
    this.globalAlphaDx = 0;
    this.timeLeftToStartFadeIn = 0;

    /*
    self.magicBgCanvas = document.createElement("canvas");
    var imageObj = new Image();
    imageObj.onload = function() {
        self.magicBgCanvas.width = imageObj.width;
        self.magicBgCanvas.height = imageObj.height;
        self.magicBgContext = self.magicBgCanvas.getContext("2d");
        self.magicBgContext.drawImage(imageObj, 0, 0);
    };
    imageObj.src = "/public/images/ATOM2.png";
    */

    this.mouseInputDevice = new MouseInputDevice(canvas);
}

Stars.prototype.reset = function() {
    if(this.globalAlphaDx > 0 || this.globalAlpha == 1) { //if in the middle of fading in or is faded in
        this.globalAlphaDx = -2.5; //start fading out
    }
    this.timeLeftToStartFadeIn = 1;
};
function spawnPosition(centerX, centerY, minRadius, maxRadius) {
    var degrees = Math.PI * (2 * Math.random());
    var x = centerX + Math.sin(degrees)*(minRadius+(maxRadius-minRadius)*Math.random());
    var y = centerY + Math.cos(degrees)*(minRadius+(maxRadius-minRadius)*Math.random());
    return {x: x, y: y};
}

Stars.prototype.spawnStar = function(centerX, centerY, big, speed, size) {
    var v = {dx:centerX - this.centerX, dy: centerY - this.centerY};
    var l = Math.sqrt(v.dx*v.dx + v.dy*v.dy);
    v = {dx:v.dx/l, dy:v.dy/l};

    return {x: centerX, y:centerY, big: big, speed: speed, size: size, v:v};
}

Stars.prototype.resetStars = function() {
    Math.seedrandom(1);

    this.stars = [];

    this.resetCanvas();
    var nbrOfStars = (this.canvas.width*this.canvas.height)*0.0008;
    var i;
    for(i = 0; i < nbrOfStars; i++) {
        this.stars.push(this.spawnStar(Math.random()*this.canvas.width, Math.random()*this.canvas.height, false, Math.random(), Math.random()));
    }
    for(i = 0; i < nbrOfStars*0.01; i++) {
        this.stars.push(this.spawnStar(Math.random()*this.canvas.width, Math.random()*this.canvas.height, true, Math.random(), Math.random()));
    }

};

Stars.prototype.resetCanvas = function() {
    this.context = this.canvas.getContext("2d");
    //temporary drawing buffer

    this.buffer = document.createElement('canvas');

    this.buffer.width = this.canvas.width;
    this.buffer.height = this.canvas.height;
    this.bufferContext = this.buffer.getContext("2d");

    this.centerX = this.canvas.width/2;
    this.centerY = this.canvas.height/2;

};

var GLOBAL_SPEED = 1;
Stars.prototype.start_gameloop = function(initial_tick) {
    var self = this;
    self.resetCanvas();
    var gameloop = new GameLoop(initial_tick);
    this.stars = [];
    self.reset();

    // Is called on each game tick.
    gameloop.ontick = function(t, dt) {
        self.timeLeftToStartFadeIn -= dt;
        self.globalAlpha += self.globalAlphaDx*dt;
        if(self.globalAlpha <= 0) { //if finished fading out
            self.globalAlpha = 0;
            if(self.timeLeftToStartFadeIn <= 0) {
                self.resetStars();        //reset stars
                self.globalAlphaDx = 1.5; //begin fading in
            }
        } else if(self.globalAlpha >= 1) { //if finished fading in
            self.globalAlpha = 1;
            self.globalAlphaDx = 0;     //stop fading in
        }

        for(var starIdx in self.stars) {
            var star = self.stars[starIdx];
            if(star.x > self.canvas.width+100 || star.y > self.canvas.height+100 || star.x < -100 || star.y < -100) {

                self.stars.splice(starIdx, 1);
                var size = Math.random();
                var pos;
                if(star.big) {
                    pos = spawnPosition(self.canvas.width/2, self.canvas.height/2, 50, Math.min(self.canvas.width, self.canvas.height)*0.2);
                } else {
                    pos = spawnPosition(self.canvas.width/2, self.canvas.height/2, 50, Math.min(self.canvas.width, self.canvas.height)*0.6);
                }
                self.stars.push(self.spawnStar(pos.x,pos.y, star.big, Math.random(), size));
            } else {
                var distX = star.x - self.centerX;
                var distY = star.y - self.centerY;
                var dist = Math.sqrt(distX*distX+distY*distY);

                if(star.big) {
                    star.x += star.speed*(star.v.dx * 0.1 * (dist*dist)/68)*dt*GLOBAL_SPEED;
                    star.y += star.speed*(star.v.dy * 0.1 * (dist*dist)/68)*dt*GLOBAL_SPEED;
                } else {
                    star.x += star.speed*(star.v.dx * 0.01 * (dist*dist)/89)*dt*GLOBAL_SPEED;
                    star.y += star.speed*(star.v.dy * 0.01 * (dist*dist)/89)*dt*GLOBAL_SPEED;
                }

            }
        }
    };

    // Is called when loop is about to start over.
    gameloop.ondone = function(t, dt, alpha) {
         // overwrite original image
        self.bufferContext.fillStyle = 'rgb(0, 0, 0)';
        self.bufferContext.fillRect(0, 0, self.canvas.width, self.canvas.height);

        self.bufferContext.fillStyle = "rgb(255, 255, 255)";
        for(var starIdx in self.stars) {
            var randomAlpha = Math.random()*0.3;

            var star = self.stars[starIdx];
            var v = {dx:star.x - self.centerX, dy: star.y - self.centerY};
            var l = Math.sqrt(v.dx*v.dx + v.dy*v.dy);
            //v = {dx:v.dx/l, dy:v.dy/l};
            var r = parseInt(255-Math.random()*30);
            var g = parseInt(220-Math.random()*10);
            var b = parseInt(220-Math.random()*10);

            var size;
            var starAlpha;
            if(star.big) {
                starAlpha = 0.08;
                size = star.size*l*0.04 + l*l*.00004;
            } else {
                starAlpha = 0.7;
                size = star.size*l*0.003 + star.size*1.9;
                //starAlpha -= randomAlpha;
            }
            var p = 1 + Math.ceil(size/5);

            for(var j = 0; j < p; j++) {
                var i = j / p;
                self.bufferContext.beginPath();
                self.bufferContext.arc(star.x, star.y, (i*size), 0, 2*Math.PI, false);
                self.bufferContext.fillStyle = "rgba(" + r +", " + g + ", " + b + ", " + starAlpha * self.globalAlpha + ")";
                self.bufferContext.fill();
            }
        }

        self.bufferContext.textBaseline = "top";
        self.bufferContext.fillStyle = 'rgb(64,128,64)';
        self.bufferContext.fillText("t: " + t, 0, 0);
        self.bufferContext.fillText("dt: " + dt, 0, 20);
        self.bufferContext.fillText("alpha: " + alpha, 0, 40);
        self.bufferContext.fillText("global alpha: " + self.globalAlpha, 0, 60);
        self.bufferContext.fillText("star count: " + self.stars.length, 0, 80);
        self.bufferContext.fillText("viewport: (" + self.canvas.width + ", " + self.canvas.height + ")", 0, 100);

        //Flush to visible canvas
        self.context.drawImage(self.buffer, 0, 0);
    };

    gameloop.start();
    self.gameloop = gameloop;

    return gameloop;
};
